import axios from 'axios';
import * as THREE from 'three';
import { lngLatToMercator, getTexture } from '../../../../three/index';
import { CSS2DObject } from 'three/examples/jsm/renderers/CSS2DRenderer';
export default class {
  mesh = new THREE.Group();
  labels: any[] = [];
  material: THREE.Material;
  constructor(url: string) {
    this.init(url);
    this.material = new THREE.MeshPhongMaterial({
      color: new THREE.Color('#ff0000')
    });
  }
  async init(url: string) {
    const res = await axios.get(url);
    const data = res.data;
    for (let i = 0; i < data.length; i++) {
      this.mesh.add(this.createMesh(data[i]));
    }
    this.mesh.position.z = 11;
  }
  createLabel(data) {
    const ele = document.createElement('div');
    ele.className = 'css2d-bar-label';
    ele.innerHTML = `<div>${data.name}</div><div>${data.value}</div>`;
    return new CSS2DObject(ele);
  }
  update(camera) {
    // const raycaster = new THREE.Raycaster();
    // this.labels.map(label => {
    //   const position = label.position.clone();
    //   position.distanceTo(camera);
    //   const labelposition = position.project(camera);
    //   // 对象在相机中的位置
    //   raycaster.setFromCamera(new THREE.Vector2(labelposition.x, labelposition.y), camera);
    //   const intersects = raycaster.intersectObject(this.mesh);
    //   if (label.name === '上海') {
    //     console.log(intersects);
    //   }
    //   // intersects.forEach(i => {
    //   //   i.object.visible = i.object.name === label.name;
    //   // });
    // });
  }
  createMesh(data) {
    const point = lngLatToMercator(data.position);
    const height = Math.max(data.value * 0.002, 1);
    const geometry = new THREE.BoxGeometry(1, 1, height);
    const mesh = new THREE.Mesh(geometry, this.material);
    const label = this.createLabel(data);
    label.name = data.name;
    label.position.set(0, 0, height / 2);
    mesh.add(label);
    mesh.position.x = point.x;
    mesh.position.y = point.y;
    mesh.position.z = height / 2;
    mesh.visible = false;
    this.labels.push(label);
    return mesh;
  }
}
